<template>
  <div class="com-content">
    <!-- 面包屑 -->
    <Header :headerData="headerData" :isGrey="true" returnText="全量发票查询" />

    <!-- 页面内容 -->
    <div class="com-full-content">
      <div class="main-content">
        <el-tabs v-model="activeName" class="demo-tabs">
          <el-tab-pane label="发票查询" name="first" />
          <el-tab-pane label="海关缴款书查询" name="second" disabled />
        </el-tabs>
        <div style="padding: 0 24px">
          <el-radio-group v-model="radioValue" style="margin: 10px 0 24px">
            <el-radio-button label="近24小时" value="1" disabled />
            <el-radio-button label="全量" value="2" />
          </el-radio-group>
          <div class="search-row">
            <el-form :inline="true" :model="search" class="demo-4">
              <el-form-item label="查询类型">
                <el-select v-model="search.s1">
                  <el-option
                    v-for="item in selectData1"
                    :key="item.value"
                    :label="item.label"
                    :value="item.value"
                  />
                </el-select>
              </el-form-item>
              <el-form-item label="发票来源">
                <el-select v-model="selectData2Val">
                  <el-option
                    v-for="item in selectData2"
                    :key="item.value"
                    :label="item.label"
                    :value="item.value"
                  />
                </el-select>
              </el-form-item>
              <el-form-item label="票种">
                <el-select>
                  <el-option
                    v-for="item in selectData"
                    :key="item.value"
                    :label="item.label"
                    :value="item.value"
                  />
                </el-select>
              </el-form-item>

              <template v-if="!searchHidden">
                <el-form-item label="发票状态">
                  <el-select
                    v-model="selectData3Val"
                    multiple
                    collapse-tags
                    :max-collapse-tags="1"
                    placeholder="请选择"
                  >
                    <el-option
                      v-for="item in selectData3"
                      :key="item.value"
                      :label="item.label"
                      :value="item.value"
                    />
                  </el-select>
                </el-form-item>
                <el-form-item label="是否正数发票">
                  <el-select>
                    <el-option
                      v-for="item in selectData"
                      :key="item.value"
                      :label="item.label"
                      :value="item.value"
                    />
                  </el-select>
                </el-form-item>
                <el-form-item label="数电票号码">
                  <el-input placeholder="请输入" />
                </el-form-item>
                <el-form-item label="发票代码">
                  <el-input placeholder="请输入" />
                </el-form-item>
                <el-form-item label="发票号码">
                  <el-input placeholder="请输入" />
                </el-form-item>
                <el-form-item label="对方纳税人识别号">
                  <el-input placeholder="请输入" />
                </el-form-item>
                <el-form-item label="对方纳税人名称">
                  <el-input placeholder="请输入" />
                </el-form-item>
                <el-form-item label="发票金额（起）">
                  <el-input placeholder="请输入" />
                </el-form-item>
                <el-form-item label="发票金额（止）">
                  <el-input placeholder="请输入" />
                </el-form-item>
                <el-form-item label="开票日期（起）">
                  <el-date-picker
                    v-model="search.date3"
                    type="date"
                    value-format="YYYY-MM-DD"
                    placeholder="请选择"
                    clearable
                  />
                </el-form-item>
                <el-form-item label="开票日期（止）">
                  <el-date-picker
                    v-model="search.date4"
                    type="date"
                    value-format="YYYY-MM-DD"
                    placeholder="请选择"
                    clearable
                  />
                </el-form-item>
              </template>

              <el-form-item class="search-col">
                <div class="flex-row-end search-btns">
                  <el-button @click="resetHandler">重置</el-button>
                  <el-button type="primary" @click="searchHandler">查询</el-button>
                  <el-button type="primary" text @click="searchHidden = !searchHidden">
                    <template v-if="searchHidden">
                      展开
                      <el-icon><ArrowDown /></el-icon>
                    </template>
                    <template v-else>
                      收起
                      <el-icon><ArrowUp /></el-icon>
                    </template>
                  </el-button>
                </div>
              </el-form-item>
            </el-form>
          </div>
          <div class="flex-row-between table-btns">
            <div class="flex-row-start">
              <el-dropdown style="margin-right: 12px" @command="handleDropChange">
                <el-button type="primary">
                  导出
                  <el-icon :size="12" class="el-icon--right">
                    <ArrowDownBold />
                  </el-icon>
                </el-button>
                <template #dropdown>
                  <el-dropdown-menu>
                    <el-dropdown-item :command="1">导出选中</el-dropdown-item>
                    <el-dropdown-item :command="2">导出全部</el-dropdown-item>
                  </el-dropdown-menu>
                </template>
              </el-dropdown>
              <el-button type="info">
                下载
                <el-icon :size="12" class="el-icon--right">
                  <ArrowDownBold />
                </el-icon>
              </el-button>
              <el-button type="info">
                批量邮箱交付
                <el-icon :size="12" class="el-icon--right">
                  <ArrowDownBold />
                </el-icon>
              </el-button>
              <el-button type="info">批量打印</el-button>
            </div>
            <el-button>自定义列</el-button>
          </div>
          <!-- <div class="flex-row-end statistics-info">
            查询结果：合计金额：
            <span data-v-0a5d4bbf="" class="info-number">39,084.08</span>
            元&emsp;合计税额：
            <span data-v-0a5d4bbf="" class="info-number">1,534.50</span>
            元
          </div> -->
          <el-table
            :data="tableData"
            style="width: 100%"
            :header-cell-style="{
              height: '49px',
              color: 'rgba(0,0,0,.4)',
              backgroundColor: '#f9fafd',
              fontWeight: 'normal',
              borderTop: '1px solid #dcdcdc',
              borderRight: '1px solid #dcdcdc',
              borderBottom: '1px solid #dcdcdc',
            }"
            @selection-change="handleSelectionChange"
          >
            <el-table-column type="selection" />
            <el-table-column label="序号" type="index" align="left" width="46" />
            <el-table-column label="票种" align="left" minWidth="150" show-overflow-tooltip>
              <template #default="scope">
                {{ scope.row.title || "-" }}
              </template>
            </el-table-column>
            <el-table-column label="发票状态" align="left" minWidth="80">
              <template #default="scope">
                <el-tag v-if="scope.row.status == 0" type="danger">
                  {{ scope.row.risk_status_text }}
                </el-tag>
                <el-tag v-else type="success">
                  {{ scope.row.risk_status_text }}
                </el-tag>
              </template>
            </el-table-column>
            <el-table-column
              label="数电票号码"
              align="left"
              minWidth="226"
              sortable
              show-overflow-tooltip
            >
              <template #default="scope">
                {{ scope.row.num || "-" }}
              </template>
            </el-table-column>
            <el-table-column label="发票代码" align="left" minWidth="120" show-overflow-tooltip>
              <template #default="scope">
                {{ scope.row.code || "-" }}
              </template>
            </el-table-column>
            <el-table-column label="发票号码" align="left" minWidth="91" show-overflow-tooltip>
              <template #default="scope">
                {{ scope.row.code_num || "-" }}
              </template>
            </el-table-column>
            <el-table-column label="发票风险等级" align="left" minWidth="103">
              <template #default="scope">
                <el-tag type="success">
                  {{ scope.row.risk_status_text }}
                </el-tag>
              </template>
            </el-table-column>
            <el-table-column label="购/销方名称" align="left" minWidth="250" show-overflow-tooltip>
              <template #default="scope">
                {{ scope.row.name || "-" }}
              </template>
            </el-table-column>
            <el-table-column
              label="购/销方识别号"
              align="left"
              minWidth="200"
              show-overflow-tooltip
            >
              <template #default="scope">
                {{ scope.row.name_num || "-" }}
              </template>
            </el-table-column>
            <el-table-column label="金额" minWidth="120" sortable align="right">
              <template #default="scope">
                {{ scope.row.money || "-" }}
              </template>
            </el-table-column>
            <el-table-column label="税额" minWidth="120" sortable align="right">
              <template #default="scope">
                {{ scope.row.tax_money || "-" }}
              </template>
            </el-table-column>
            <el-table-column label="价税合计" minWidth="120" sortable align="right">
              <template #default="scope">
                {{ scope.row.price || "-" }}
              </template>
            </el-table-column>
            <el-table-column label="特定业务类型" align="left" minWidth="120">
              <template #default="scope">
                {{ scope.row.type || "" }}
              </template>
            </el-table-column>
            <el-table-column label="开票日期" align="left" minWidth="180" sortable>
              <template #default="scope">
                {{ scope.row.date || "-" }}
              </template>
            </el-table-column>
            <el-table-column label="发票来源" align="left" minWidth="120">
              <template #default="scope">
                {{ scope.row.source || "-" }}
              </template>
            </el-table-column>
            <el-table-column label="开票人" align="left" minWidth="120">
              <template #default="scope">
                {{ scope.row.drawer || "-" }}
              </template>
            </el-table-column>
            <el-table-column label="操作" align="left" width="150" fixed="right">
              <el-button
                type="primary"
                text
                style="padding-left: 0; margin: 0"
                @click="goPath('/empty')"
              >
                详情
              </el-button>
              <el-button
                type="primary"
                text
                style="padding-left: 0; margin: 0"
                @click="goPath('/empty')"
              >
                预览
              </el-button>
              <el-button
                type="primary"
                text
                style="padding-left: 0; margin: 0"
                @click="goPath('/empty')"
              >
                下载
              </el-button>
            </el-table-column>
          </el-table>
          <el-pagination
            v-model:currentPage="search.pageNo"
            v-model:page-size="search.pageSize"
            :page-sizes="[10, 20, 30, 40]"
            layout="total, sizes, prev, pager, next, jumper"
            :total="total"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
          />
        </div>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { reactive, ref, onMounted } from "vue";
import Http from "@/utils/api";
import { httpsUrl } from "@/utils/httpsUrl";
import { ElMessage, ElMessageBox } from "element-plus";
import { useRouter } from "vue-router";
const rout = useRouter();
const headerData = ref<any>({
  title: "全量发票查询",
  type: 2,
  list: [
    { title: "发票业务", url: "" },
    { title: "发票查询统计", url: "" },
  ],
});

const activeName = ref("first");
const radioValue = ref("2");

const selectData1 = [
  { value: "1", label: "开具发票" },
  { value: "2", label: "取得发票" },
];
const selectData2 = [{ value: "1", label: "全部" }];
const selectData2Val = ref("1");

const selectData3 = [
  { value: "1", label: "正常" },
  { value: "2", label: "已作废" },
  { value: "3", label: "已冲红-全额" },
  { value: "4", label: "已冲红-部分" },
];
const selectData3Val = ref(["1", "2", "3", "4"]);

const selectData = ref<any>([]); // 空下拉列表
const dropType = ref(1); // 导出类型1=选中，2=全部
const tableData = ref<any>([]); // 列表数据
const total = ref(0); // 分页总条目
const multipleSelection = ref([]); // 选择的条目id集合
const searchHidden = ref(false); // 是否隐藏搜索条件
const search = ref<any>({
  s1: "1",
  s2: ["1", "3"],
  s3: "2",
  date1: "",
  date2: "",
  date3: "",
  date4: "",
  pageSize: 10,
  pageNo: 1,
});

// table点击选择条目
const handleSelectionChange = (val: any) => {
  let arr: any = [];
  val.map((item: any) => {
    arr.push(item.id);
  });
  multipleSelection.value = arr;
};

// 获取table列表
function getDataList() {
  let params = {
    dd_type: search.value.s1,
    startTime: search.value.date3,
    endTime: search.value.date4,
    page: search.value.pageNo,
    limit: search.value.pageSize,
  };
  Http.Get("api3", params).then((res: any) => {
    if (res.code == 1) {
      tableData.value = res.data.data;
      total.value = res.data.total;
    }
  });
}
// 分页操作
const handleSizeChange = (val: number) => {
  search.value.pageSize = val;
  getDataList();
};
const handleCurrentChange = (val: number) => {
  search.value.pageNo = val;
  getDataList();
};
// 搜索
const searchHandler = () => {
  search.value.pageNo = 1;
  search.value.pageSize = 10;
  getDataList();
  // 缓存查询日期
  localStorage.setItem("searcha14", JSON.stringify(search.value));
};
// 重置
const resetHandler = () => {
  search.value = {};
  search.value.s1 = "";
  search.value.s2 = ["1", "3"];
  search.value.s3 = "2";
  search.value.pageNo = 1;
  search.value.pageSize = 10;
  initDate(1);
  getDataList();
};

// 获取当前月的第一天的日期，以及当前的日期
const initDate = (tag: any) => {
  const now = new Date();
  const firstDay = new Date(now.getFullYear(), now.getMonth(), 1);

  // 如果有缓存日期
  if (localStorage.getItem("searcha14") && !tag) {
    const searchData = JSON.parse(localStorage.getItem("searcha14") ?? "{}");
    search.value.date3 = searchData.date3;
    search.value.date4 = searchData.date4;
    return;
  }

  // search.value.date3 = firstDay.toLocaleDateString("sv"); // 'sv' locale uses YYYY-MM-DD format
  // search.value.date4 = now.toLocaleDateString("sv");
};

// 提示
function onTip() {
  ElMessageBox.alert("页面正在缓冲中....", "提示", {
    confirmButtonText: "好的",
    callback: () => {},
  });
}

// 跳转空页面
function goPath(url: any) {
  const resolved = rout.resolve({ path: url });
  window.open(resolved.href, "_blank");
}

function handleDropChange(res: any) {
  dropType.value = res;
  if (res == 1) {
    if (multipleSelection.value.length == 0) {
      ElMessage({
        message: "请选择要导出的条目",
        type: "warning",
      });
      return;
    } else {
      downloadExcel();
    }
  }

  if (res == 2) {
    downloadExcel();
  }
}

// 导出
interface ExportParams {
  startTime?: string;
  endTime?: string;
  ids?: string;
}
function downloadExcel() {
  let params: ExportParams = {
    startTime: search.value.date3,
    endTime: search.value.date4,
  };

  if (params.startTime == "" || params.endTime == "") {
    ElMessage({
      message: "请选择时间范围",
      type: "warning",
    });
    return;
  }

  if (dropType.value == 1) {
    // 动态添加 ids 属性
    params.ids = multipleSelection.value.join(",");
  }

  // 构建导出链接
  const token = localStorage.getItem("TOKEN_KEY") || "";
  let exportUrl = `${httpsUrl.API_URL}/${httpsUrl.api8}?X-Access-Token=${token}&startTime=${params.startTime}&endTime=${params.endTime}`;
  if (dropType.value == 1 && params.ids) {
    exportUrl += `&ids=${params.ids}`;
  }
  console.log(exportUrl, "导出");

  // 创建并触发下载链接
  const a = document.createElement("a");
  a.href = exportUrl;
  a.target = "_blank";
  document.body.appendChild(a);
  a.click();
  document.body.removeChild(a);
}

// 生命周期
onMounted(() => {
  localStorage.removeItem("searcha6");
  localStorage.removeItem("searcha15");
  initDate(0);
  getDataList();
});
</script>

<style lang="scss" scoped>
@use "./css/style";

:deep(.el-button--info) {
  color: rgb(0 0 0 / 90%);
  background-color: #e7e7e7;
  border-color: #e7e7e7;
}

:deep(.el-table) {
  th:last-child {
    border-right: none !important;
  }

  td {
    font:
      14px / 22px "PingFang SC",
      "Microsoft YaHei",
      "Arial Regular",
      sans-serif;
    color: rgb(0 0 0 / 90%);
    border-color: #dcdcdc;
  }

  .cell {
    padding: 0 8px;
  }

  .caret-wrapper {
    float: right;
    height: 16px;
    margin-top: 4px;
  }

  .sort-caret {
    border-width: 4px;
  }
}

:deep(.el-tag) {
  &.el-tag--success {
    color: #00a870;
    background-color: #e8f8f2;
    border-color: #e8f8f2;
  }
}

:deep(.el-radio-button) {
  &.is-active .el-radio-button__original-radio:not(:disabled) + .el-radio-button__inner {
    color: #4285f4;
    background-color: #fff;
    border-color: #4285f4;
  }
}
</style>
